package com.yang.mybatis.session;

import com.yang.mybatis.config.MybatisDataSource;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public abstract class TransactionInvoke<T> {
    public T invoke(MybatisDataSource mybatisDataSource) {
        String username = mybatisDataSource.getUsername();
        String password = mybatisDataSource.getPassword();
        String url = mybatisDataSource.getUrl();
        String driver = mybatisDataSource.getDriver();

        Connection connection = null;
        T result = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
            connection.setAutoCommit(false);
            result = execute(connection);
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            closeResource(connection);
        }
        return result;
    }

    private void closeResource(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }

    public abstract T execute(Connection connection) throws SQLException;
}
